﻿Option Explicit On
'Option Strict On
Imports System.Collections.ObjectModel
Imports System.Management
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Text
Imports System.IO
Imports System
Imports System.DirectoryServices
Imports System.Diagnostics
Imports System.Threading
Imports System.DirectoryServices.AccountManagement
Imports System.ComponentModel
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Runtime.InteropServices
Imports System.Data.SqlClient
Imports System.Security.Principal
Imports System.Security.AccessControl
Imports System.Security
Imports ActiveDs
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Imports System.Xml

Module Module1


    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    Const EVENT_SUCCESS = 0
    Const EVENT_ERROR = 1
    Const EVENT_INFORM = 4



    ' Constants taken from ADS_GROUP_TYPE_ENUM
    Const ADS_GROUP_TYPE_GLOBAL_GROUP = 2
    Const ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = 4
    Const ADS_GROUP_TYPE_SECURITY_ENABLED = -2147483648
    Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = 8

    Const ADS_PROPERTY_CLEAR = 1  'Clears the value (or values) from the specified attribute.
    Const ADS_PROPERTY_UPDATE = 2 'Replaces the value in the specified attribute with new values.
    Const ADS_PROPERTY_APPEND = 3 'Appends a new value (or values) to the specified attribute.
    Const ADS_PROPERTY_DELETE = 4 'Deletes the value (or values) from the specified attribute.

    Dim DBServer As String
    Dim DBName As String

    ' define variables for Departments
    Dim intDPDepartmentID() As Integer
    Dim strDPDepartmentName() As String
    Dim strDPFullDepartmentName() As String
    Dim intDPDepartmentLevel() As Integer
    Dim intDPParentDepartmentID() As Integer
    Dim strDPDateValid() As String
    Dim strDPManagedBy() As String
    Dim strDPRegion() As String
    Dim strDPCountry() As String
    Dim strDPCountryCode() As String
    Dim strDPCountryAbr() As String
    Dim strDPCity() As String
    Dim strDPStreet() As String
    Dim strDPPostalCode() As String
    Dim strOutputFileOULog, strOutputFileMoveOULog, strOutputFileUpdateOULog As New StringBuilder
    Dim strOutputFileCreateOULog, strOutputFileMoveEmptyNonHROULog As New StringBuilder
    Dim strOutputFileErrorOULog, strOutputFileRenameOULog, strOutputFileNonHROULog As New StringBuilder

    ' define variables for employees
    Dim strCompany(), strCompanyID() As String
    Dim strEmployeeID(), strLastName() As String
    Dim strGivenName(), strMiddleName() As String
    Dim strBirthDate(), strTitleID() As String
    Dim strDateValid(), strPhone() As String
    Dim strJobTitle(), strFullJobTitle() As String
    Dim strEmployeeType(), strEmployeeNumber() As String
    Dim strDepartmentID(), strDepartment(), strFullDepartmentName() As String
    Dim strManagerID() As String
    Dim strRegion(), strCountry(), strCountryCode(), strCountryAbr() As String
    Dim strCity(), strStreet(), strPostalCode() As String
    Dim strOutputFileUserLog, strOutputFileMoveUserLog, strOutputFileErrorUserLog, OutputFileErrorUserLog, strOutputFileRenameUserLog As New StringBuilder
    Dim strOutputFileCreateUserLog, strOutputFileUpdateUserLog, OutputFileMoveFiredLog, OutputFileAddUsersToGroupsLog As New StringBuilder

    Dim strSMTP_Server As String
    Dim strA As String = """"
    Dim strB As String = "\"
    Dim strC As String = ","
    Dim strD As String = String.Empty

    Dim intQuantityLines_DP, intQuantityLines_User, intQuantityLines_DP_AD, intQuantityLines_User_AD As Integer
    Dim strPart, strTime, strCommonLogOUPath, strTodayLogOUPath As String

    Dim strDNameCurrentOU As String
    Dim strCommonLogPath, strHRSync, strNetBiosName, strSender, strRecipient, strRoot, strRootDG As String
    Dim strCommonLogUserPath, strTodayLogUserPath As String
    Dim strUPN, strMailDataBase, strRootHomeDir As String
    Dim strRoot11, strRoot12, strRoot21, strRoot22, strRootAD, strRootDFS, strServerDFS1, strServerDFS2, strDFSNameSpaceServer As String
    Dim counter, l, m As Integer



    Dim strDNCurrentOU, strDNCurrentParentOU As String

    Dim intCounterCreateOU, intCounterUpdateOU, intCounterRenameOU, intCounterMoveOU, intCounterNonHRMoveOU As New Integer
    Dim intCounterCreateUser, intCounterUpdateUser, intCounterRenameUser, intCounterMoveUser, intCounterMoveFiredUser, intCounterNonHRMoveUser As New Integer
    Dim intCurrentEmployeeCounter, intCurrentOUCounter As Integer



    Dim strFullName() As String
    Dim strCurrentFullName, strCurrentDN As String
    '----------------------------------------------------------


    Dim xml As New XmlDocument

    ' инициализация переменных

    Dim strToday As String = Right(Date.Now.ToString, 4) + Mid(Date.Now.ToString, 4, 2) + Left(Date.Now.ToString, 2)
    Dim intHour As Integer = Hour(CDate(Date.Now.ToString))
    Dim strDNParentOU As String
    Dim FILE_NAME As String = "C:\Logs\main.txt"
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, False)
    Dim strStartTimeMain, strStartTimeOUAD, strStartTimeOUDFS, strStartTimeGroupAD, strStartTimeGroupDFS, strStartTimeUsers As DateTime
    Dim strEndTimeMain, strEndTimeOUAD, strEndTimeOUDFS, strEndTimeGroupAD, strEndTimeGroupDFS, strEndTimeUsers As DateTime
    Dim strStartTimeDir, strEndTimeDir, strStartTimeDFS, strEndTimeDFS As DateTime


    Sub Main()

        strStartTimeMain = DateTime.Now
        Console.WriteLine("Start Time: {0}", strStartTimeMain.ToString)
        strTime = DateTime.Now.ToString
        Dim strFormat As String = "yyyyMMdd"

        ' Create an EventLog instance and assign its source. 
        WriteToEventLog("Departments parsing application was started.")

        Select Case intHour
            Case 10 To 13
                strPart = "2"
            Case 14 To 17
                strPart = "3"
            Case 18 To 23
                strPart = "4"
            Case Else
                strPart = "1"
        End Select

        strToday = Now.ToString(strFormat)
        strCommonLogPath = "C:\Logs\"
        strCommonLogPath = "C:\Logs\"                                                '	
        DBServer = "localhost\SQLEXPRESS"
        DBName = "HR_Test"
        strRoot = "DC=contoso,DC=local"
        strRootAD = "OU=Contoso,OU=Organizations,DC=contoso,DC=local"
        strHRSync = "OU=Sync_HR,OU=_Disabled Users,DC=contoso,DC=local"
        strSMTP_Server = "172.31.182.111"
        strRootHomeDir = "\\contoso.local\DFS\Contoso\User Home Folders\"
        strUPN = "@contoso.local"

        strCommonLogOUPath = strCommonLogPath & "OU\"
        strTodayLogOUPath = strCommonLogOUPath & strToday & "\"
        If Not (Directory.Exists(strCommonLogOUPath)) Then
            Directory.CreateDirectory(strCommonLogOUPath)
        End If
        If Not (Directory.Exists(strTodayLogOUPath)) Then
            Directory.CreateDirectory(strTodayLogOUPath)
        End If
        strCommonLogUserPath = strCommonLogPath & "Users\"
        strTodayLogUserPath = strCommonLogUserPath & strToday & "\"
        If Not (Directory.Exists(strCommonLogUserPath)) Then
            Directory.CreateDirectory(strCommonLogUserPath)
        End If
        If Not (Directory.Exists(strTodayLogUserPath)) Then
            Directory.CreateDirectory(strTodayLogUserPath)
        End If
        If Not CheckOUbyDN("OU=" & strToday & "_" & strPart & "," & strHRSync, strRoot) Then
            'sb.AppendLine(strToday & "_" & strPart)
            Dim objOU As DirectoryEntry
            Dim strPath As String          ' Binding path.

            strPath = "LDAP://" & strHRSync
            Using de As New DirectoryEntry(strPath)
                de.RefreshCache()

                Try
                    objOU = de.Children.Add("OU=" & strToday & "_" & strPart, "OrganizationalUnit")
                    objOU.Properties("description").Add("Users and OU, that moved in this OU")
                    objOU.CommitChanges()
                    objOU.Dispose()
                Catch ex As Exception
                End Try
            End Using
        End If

        GetDataDepartmentsFromSQL()
        GetDataUsersFromSQL()

        strStartTimeOUAD = DateTime.Now
        Console.WriteLine("Start AD part")
        'Console.WriteLine("Start Time: {0}", strStartTimeOUAD.ToString)
        Call OU_Management(strRootAD, "", "OU")
        strEndTimeOUAD = DateTime.Now
        'Console.WriteLine("End Time: {0}", strEndTimeOUAD.ToString)
        Console.WriteLine("AD OU Time : {0}", TimeDiff(strStartTimeOUAD, strEndTimeOUAD)) 'output 16 mins in format 00:16:00

        strStartTimeUsers = DateTime.Now
        Console.WriteLine("Start User Management")
        'Console.WriteLine("Start Time: {0}", strStartTimeUsers.ToString)
        Call User_Management()
        strEndTimeUsers = DateTime.Now
        'Console.WriteLine("End Time: {0}", strEndTimeUsers.ToString)
        Console.WriteLine("Users Time : {0}", TimeDiff(strStartTimeUsers, strEndTimeUsers)) 'output 16 mins in format 00:16:00



        strEndTimeMain = DateTime.Now
        Console.WriteLine("Main Time : {0}", TimeDiff(strStartTimeMain, strEndTimeMain)) 'output 16 mins in format 00:16:00

        Dim cki As ConsoleKeyInfo
        ' Prevent example from ending if CTL+from is pressed.
        Console.TreatControlCAsInput = True

        Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.")
        Console.WriteLine("Press the Escape (Esc) key to quit: " + vbCrLf)
        Do
            cki = Console.ReadKey()
            Console.Write(" --- You pressed ")
            If (cki.Modifiers And ConsoleModifiers.Alt) <> 0 Then Console.Write("ALT+")
            If (cki.Modifiers And ConsoleModifiers.Shift) <> 0 Then Console.Write("SHIFT+")
            If (cki.Modifiers And ConsoleModifiers.Control) <> 0 Then Console.Write("CTL+")
            Console.WriteLine(cki.Key)
        Loop While cki.Key <> ConsoleKey.Escape

    End Sub



    Sub GetDataDepartmentsFromSQL()
        Dim SQLStr As String
        Dim ConnString As String
        Using SQLConn As New SqlConnection() 'The SQL Connection
            Using SQLCmd As New SqlCommand() 'The SQL Command


                ConnString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" & DBName & ";Data Source=" & DBServer & ";"
                SQLConn.ConnectionString = ConnString 'Set the Connection Str
                SQLConn.Open() 'Open the connection

                'SQLStr = "Exec UpdateDepartments"
                SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
                'SQLCmd.CommandText = SQLStr 'Sets the SQL String
                'SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only                SQLStr = "Select adminDescription,from,co,countryCode,description,distinguishedName,l,managedBy,name,OU,postalCode,st,street,x121Address from DepartmentsAD Order by x121Address"
                'Select [department_id] ,[department_name] ,[manager_id],[parentDepartment_id],[departmentlevel],[date_valid],[street_address],[postal_code],[city],[state_province],[country_name],[country_code],[country_abr]  FROM [HR_Test].[dbo].[departments]
                SQLStr = "Select [department_id] ,[department_name] ,[manager_id],[parentDepartment_id],[departmentlevel],[date_valid],[street_address],[postal_code],[city],[state_province],[country_name],[country_code],[country_abr] from Departments Order by DepartmentLevel"
                SQLCmd.CommandText = SQLStr 'Sets the SQL String
                Using SQLdr As SqlDataReader = SQLCmd.ExecuteReader 'Gets Data

                    While SQLdr.Read() 'While Data is Present        


                        ReDim Preserve intDPDepartmentID(counter)
                        ReDim Preserve strDPDepartmentName(counter)
                        ReDim Preserve strDPFullDepartmentName(counter)
                        ReDim Preserve intDPDepartmentLevel(counter)
                        ReDim Preserve intDPParentDepartmentID(counter)
                        ReDim Preserve strDPDateValid(counter)
                        ReDim Preserve strDPManagedBy(counter)
                        ReDim Preserve strDPRegion(counter)
                        ReDim Preserve strDPCountry(counter)
                        ReDim Preserve strDPCountryCode(counter)
                        ReDim Preserve strDPCountryAbr(counter)
                        ReDim Preserve strDPCity(counter)
                        ReDim Preserve strDPStreet(counter)
                        ReDim Preserve strDPPostalCode(counter)

                        ' 	обнуляем данные перед считыванием
                        intDPDepartmentID(counter) = 0
                        strDPDepartmentName(counter) = String.Empty
                        strDPFullDepartmentName(counter) = String.Empty
                        intDPDepartmentLevel(counter) = 0
                        intDPParentDepartmentID(counter) = 0
                        strDPDateValid(counter) = String.Empty
                        strDPManagedBy(counter) = CStr(0)
                        strDPRegion(counter) = String.Empty
                        strDPCountry(counter) = String.Empty
                        strDPCountryCode(counter) = String.Empty
                        strDPCountryAbr(counter) = String.Empty
                        strDPCity(counter) = String.Empty
                        strDPStreet(counter) = String.Empty
                        strDPPostalCode(counter) = String.Empty

                        '	считывание массива
                        intDPDepartmentID(counter) = CInt(SQLdr("department_id"))
                        strDPDepartmentName(counter) = CStr(SQLdr("department_name"))
                        strDPDepartmentName(counter) = UCase(Left(strDPDepartmentName(counter), 1)) & LCase(Right(strDPDepartmentName(counter), Len(strDPDepartmentName(counter)) - 1))
                        strDPDepartmentName(counter) = Replace(strDPDepartmentName(counter), strA, strB)
                        strDPDepartmentName(counter) = Replace(strDPDepartmentName(counter), strC, strD)
                        strDPFullDepartmentName(counter) = CStr(SQLdr("department_name"))
                        intDPDepartmentLevel(counter) = CInt(SQLdr("departmentlevel"))
                        intDPParentDepartmentID(counter) = CInt(SQLdr("parentDepartment_id"))
                        If Not IsDBNull(SQLdr("manager_id")) Then
                            strDPManagedBy(counter) = SQLdr("manager_id").ToString
                        End If
                        strDPDateValid(counter) = CStr(SQLdr("date_valid"))
                        strDPRegion(counter) = CStr(SQLdr("state_province"))
                        strDPCountry(counter) = CStr(SQLdr("country_name"))
                        strDPCountryCode(counter) = CStr(SQLdr("country_code"))
                        strDPCountryAbr(counter) = CStr(SQLdr("country_abr"))
                        strDPCity(counter) = CStr(SQLdr("city"))
                        strDPStreet(counter) = CStr(SQLdr("street_address"))
                        strDPPostalCode(counter) = CStr(SQLdr("postal_code"))


                        objWriter.WriteLine(intDPDepartmentID(counter) & ";" & intDPParentDepartmentID(counter) & ";" & intDPDepartmentLevel(counter) _
                         & ";" & strDPDepartmentName(counter) & ";" & strDPManagedBy(counter) & ";" & strDPDateValid(counter))
                        counter = counter + 1
                        'objRst.MoveNext()
                    End While

                    'Loop While SQLdr.NextResult() 'Move to the Next Record
                End Using                'Close the SQLDataReader        
            End Using
        End Using
        intQuantityLines_DP = counter - 1
        Console.WriteLine("intQuantityLines_DP : {0}", intQuantityLines_DP + 1)
    End Sub
    Public Function WriteToEventLog(ByVal Entry As String, _
   Optional ByVal AppName As String = "RIDM", _
   Optional ByVal EventType As  _
   EventLogEntryType = EventLogEntryType.Information, _
   Optional ByVal LogName As String = "Application") As Boolean

        '*************************************************************
        'PURPOSE: Write Entry to Event Log using VB.NET
        'PARAMETERS: Entry - Value to Write
        '            AppName - Name of Client Application. Needed 
        '              because before writing to event log, you must 
        '              have a named EventLog source. 
        '            EventType - Entry Type, from EventLogEntryType 
        '              Structure e.g., EventLogEntryType.Warning, 
        '              EventLogEntryType.Error
        '            LogName: Name of Log (System, Application; 
        '              Security is read-only) If you 
        '              specify a non-existent log, the log will be
        '              created

        'RETURNS:   True if successful, false if not

        'EXAMPLES: 
        '1. Simple Example, Accepting All Defaults
        '    WriteToEventLog "Hello Event Log"

        '2.  Specify EventSource, EventType, and LogName
        '    WriteToEventLog("Danger, Danger, Danger", "MyVbApp", _
        '                      EventLogEntryType.Warning, "System")
        '
        'NOTE:     EventSources are tightly tied to their log. 
        '          So don't use the same source name for different 
        '          logs, and vice versa
        '******************************************************

        Dim objEventLog As New EventLog()

        ' Try
        'Register the App as an Event Source
        If Not EventLog.SourceExists(AppName) Then

            EventLog.CreateEventSource(AppName, LogName)
        End If

        objEventLog.Source = AppName

        'WriteEntry is overloaded; this is one
        'of 10 ways to call it
        objEventLog.WriteEntry(Entry, EventType)
        Return True
        'Catch Ex As Exception
        'Return False

        'End Try

    End Function

    Public Function CheckOUbyDN(ByVal strDN As String, ByVal strRootIn As String) As Boolean
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.

        ' Construct the binding string.
        strPath = "LDAP://" & strRootIn

        ' Specify filter.
        strFilter = "(&(objectClass=OrganizationalUnit)(distinguishedName=" & strDN & "))"

        ' Get AD LDS object.

        Using de = New DirectoryEntry(strPath)
            de.RefreshCache()
            ' Get search object,
            '  specify filter and scope,
            '  perform search.
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.SearchScope = SearchScope.Subtree
                Using objSearchResults = objSearchADAM.FindAll()
                    ' Enumerate filtered objects.
                    If objSearchResults.Count <> 0 Then
                        Return True
                    Else
                        Return False
                    End If
                End Using
            End Using
        End Using
    End Function
    Public Function CheckUserbyDN(ByVal strDN As String, ByVal strRootIn As String) As Boolean
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.
        Dim objResult As SearchResult

        ' Construct the binding string.
        strPath = "LDAP://" & strRootIn

        ' Specify filter.
        strFilter = "(&(objectCategory=person)(objectClass=user)(distinguishedName=" & strDN & "))"

        ' Get AD LDS object.
        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.PropertiesToLoad.Add("distinguishedName")
                objSearchADAM.SearchScope = SearchScope.Subtree
                ' Enumerate filtered objects.
                Try
                    objResult = objSearchADAM.FindOne()
                    If Not IsNothing(objResult) Then
                        Return True
                    Else
                        Return False
                    End If
                Catch ex As Exception
                    Return False
                End Try
            End Using
        End Using
        Return True
    End Function

    Public Function GetDN_OU_byID(ByVal strID As String, ByVal strRootIn_ForGet As String) As String
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.
        Dim objResult As SearchResult
        ' Construct the binding string.
        strPath = "LDAP://" & strRootIn_ForGet

        ' Specify filter.
        strFilter = "(&(objectClass=OrganizationalUnit)(x121Address=" & strID & "))"

        ' Get AD LDS object.
        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.PropertiesToLoad.Add("distinguishedName")
                objSearchADAM.SearchScope = SearchScope.Subtree
                ' Enumerate filtered objects.
                Try
                    objResult = objSearchADAM.FindOne()
                    If Not IsNothing(objResult) Then
                        Return CStr(objResult.Properties("distinguishedName")(0))
                    Else
                        Return String.Empty
                    End If
                Catch ex As Exception

                End Try
            End Using
        End Using
    End Function
    Public Function GetDN_OU_byNameWithoutID(ByVal strNameIn As String, ByVal strRootIn_ForGet As String) As String
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.

        ' Construct the binding string.
        strPath = "LDAP://" & strRootAD
        'sb.AppendLine("Bind to: {0}", strPath)

        ' Specify filter.
        strFilter = "(&(objectCategory=OrganizationalUnit)(OU=" & strNameIn & "' and x121Address<>'*'" & "))"
        'sb.AppendLine("Filter:  {0}", strFilter)

        ' Get AD LDS object.
        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.PropertiesToLoad.Add("distinguishedName")
                objSearchADAM.SearchScope = SearchScope.Subtree
                ' Enumerate filtered objects.
                Try
                    Dim objResult = objSearchADAM.FindOne()
                    If Not IsNothing(objResult) Then
                        GetDN_OU_byNameWithoutID = CStr(objResult.Properties("distinguishedName")(0))
                    Else
                        GetDN_OU_byNameWithoutID = String.Empty
                    End If
                Catch ex As Exception

                End Try
            End Using
        End Using

    End Function
    Public Function CreateOU(ByVal IntConter As Integer, ByVal strTypeOU_ForCreate As String, ByVal strRootIn_ForCreate As String, ByVal strTable As String, ByVal strPrefix As String)
        Dim strParentDepartmentID_ForCreate As String = strTypeOU_ForCreate & CStr(intDPParentDepartmentID(IntConter))
        Dim strDepartmentID_ForCreate As String = strTypeOU_ForCreate & CStr(intDPDepartmentID(IntConter))
        Dim strDepartmentName_ForCreate As String = strDPDepartmentName(IntConter)
        Dim strFullDepartmentName_ForCreate As String = strDPFullDepartmentName(IntConter)
        Dim strManagedBy_ForCreate As String = strDPManagedBy(IntConter)
        Dim strDateValid_Create As String = strDPDateValid(IntConter)
        Dim strRegion_ForCreate As String = strDPRegion(IntConter)
        Dim strCity_ForCreate As String = strDPCity(IntConter)
        Dim strStreet_ForCreate As String = strDPStreet(IntConter)
        Dim strPostalCode_ForCreate As String = strDPPostalCode(IntConter)
        Dim strCountry_ForCreate As String = strDPCountry(IntConter)
        Dim strCountryCode_ForCreate As String = strDPCountryCode(IntConter)
        Dim strCountryAbr_ForCreate As String = strDPCountryAbr(IntConter)
        Dim strDPDN_ForCreate As String
        Dim objOU As DirectoryEntry
        Dim strPath As String          ' Binding path.
        Dim strParentOU As String
        strParentOU = GetDN_OU_byID(strParentDepartmentID_ForCreate, strRootIn_ForCreate)
        If strParentOU <> String.Empty Then
            strDPDN_ForCreate = "OU=" & strDepartmentName_ForCreate & "," & strParentOU
            strPath = "LDAP://" & strParentOU
            Using de As New DirectoryEntry(strPath)
                de.RefreshCache()

                Try
                    objOU = de.Children.Add("OU=" & strDepartmentName_ForCreate, "OrganizationalUnit")
                    objOU.CommitChanges()
                    Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Created OU " & strDepartmentName_ForCreate & " with number  " & strDepartmentID_ForCreate & " and full name " & strFullDepartmentName_ForCreate)
                    strOutputFileCreateOULog.AppendLine(Now.ToString & " ; Created OU " & strDepartmentName_ForCreate & " with number  " & strDepartmentID_ForCreate & " and full name " & strFullDepartmentName_ForCreate)
                    intCounterCreateOU = intCounterCreateOU + 1
                Catch ex As Exception
                    Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error creating OU " & strDepartmentName_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                    strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error creating OU " & strDepartmentName_ForCreate & "; " & strFullDepartmentName_ForCreate & "; " & ex.Message)
                    Return False
                End Try

                If strFullDepartmentName_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("description").Add(strFullDepartmentName_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value description " & strFullDepartmentName_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value description " & strFullDepartmentName_ForCreate)

                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value description " & strFullDepartmentName_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value description " & strFullDepartmentName_ForCreate & "; " & strFullDepartmentName_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strDepartmentID_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("x121Address").Add(strDepartmentID_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value x121Address " & strDepartmentID_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value x121Address " & strDepartmentID_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value x121Address " & strDepartmentID_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value x121Address " & strFullDepartmentName_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strDateValid_Create <> String.Empty Then
                    Try
                        objOU.Properties("adminDescription").Add(strDateValid_Create)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value adminDescription " & strDateValid_Create)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value adminDescription " & strDateValid_Create)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value adminDescription " & strDepartmentID_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value adminDescription " & strFullDepartmentName_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strRegion_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("st").Add(strRegion_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value st " & strRegion_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value st " & strRegion_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value st " & strRegion_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value st " & strRegion_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strCity_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("l").Add(strCity_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value l " & strCity_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value l " & strCity_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value l " & strCity_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value l " & strCity_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If


                If strStreet_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("street").Add(strStreet_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value streetAddress " & strStreet_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value street " & strStreet_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value streetAddress " & strStreet_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value streetAddress " & strStreet_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strPostalCode_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("postalCode").Add(strPostalCode_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value postalCode " & strPostalCode_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value postalCode " & strPostalCode_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value postalCode " & strPostalCode_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value postalCode " & strPostalCode_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strCountry_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("co").Add(strCountry_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value co " & strCountry_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value co " & strCountry_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value co " & strCountry_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value co " & strCountry_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strCountryCode_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("countryCode").Add(strCountryCode_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value countryCode " & strCountryCode_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value countryCode " & strCountryCode_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value countryCode " & strCountryCode_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value countryCode " & strCountryCode_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strCountryAbr_ForCreate <> String.Empty Then
                    Try
                        objOU.Properties("c").Add(strCountryAbr_ForCreate)
                        objOU.CommitChanges()
                        Call WriteToSQL_Logs(strTable, strPrefix & "Create", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Written down value from " & strCountryAbr_ForCreate)
                        strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullDepartmentName_ForCreate & "; Written down value c " & strCountryAbr_ForCreate)
                    Catch ex As Exception
                        Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value from " & strCountryAbr_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value c " & strCountryAbr_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                    End Try
                End If

                If strManagedBy_ForCreate <> String.Empty Then
                    Dim strManagerDN = GetDN_User_byID(strManagedBy_ForCreate, strRootAD)
                    If strManagerDN <> String.Empty Then
                        Try
                            objOU.Properties("managedBy").Add(strManagerDN)
                            objOU.CommitChanges()
                            Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, strDPDN_ForCreate & "; Written down value OU managedBy " & strManagerDN)
                            strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strDPDN_ForCreate & "; Written down valueOU managedBy " & strManagerDN)
                        Catch ex As Exception
                            Call WriteToSQL_Logs(strTable, "OUError", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value  OU managedBy " & ex.Message)
                            strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value OU managedBy " & ex.Message)
                        End Try
                    End If
                End If
            End Using

        Else
            Call WriteToSQL_Logs(strTable, strPrefix & "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error in creating OU " & strDepartmentName_ForCreate & "; " & strDepartmentName_ForCreate & ";  Parent OU doesnt exist")
            strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error in creating OU " & strDepartmentName_ForCreate & "; " & strFullDepartmentName_ForCreate & ";  Parent OU doesnt exist")
            Return False
        End If
        Return True
    End Function
    Function WriteToSQL_Logs(ByVal strTableIn As String, ByVal strLog As String, ByVal strID As String, ByVal strOU As String, ByVal strEvent As String)
        Dim SQLStr As String
        Dim ConnString As String
        Using SQLConn As New SqlConnection() 'The SQL Connection
            Using SQLCmd As New SqlCommand() 'The SQL Command
                ConnString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" & DBName & ";Data Source=" & DBServer & ";"
                SQLStr = "INSERT INTO [" & DBName & "].[dbo].[" & strTableIn & "]  Values (GETDATE()," & Chr(39) & strID & Chr(39) & "," & Chr(39) & strOU & Chr(39) & "," & Chr(39) & strEvent & Chr(39) & "," & Chr(39) & strLog & Chr(39) & ")"
                SQLConn.ConnectionString = ConnString 'Set the Connection Str
                SQLConn.Open() 'Open the connection
                SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
                SQLCmd.CommandText = SQLStr 'Sets the SQL String
                SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
            End Using
        End Using
    End Function

    Function MoveOU(ByVal strSorceOU_ForMove As String, ByVal strTargetOU_ForMove As String, ByVal strNameOU_ForMove As String, ByVal strId As String, ByVal strRootIn_ForMove As String, ByVal strTable As String, ByVal strPrefix As String)

        Dim strOldParentDN, strNewParentDN As String
        strNewParentDN = strTargetOU_ForMove


        If CheckOUbyDN(strTargetOU_ForMove, strRootIn_ForMove) Then
            strOldParentDN = Right(strSorceOU_ForMove, Len(strSorceOU_ForMove) - InStr(strSorceOU_ForMove, ",OU="))
            Using OldOU As New DirectoryEntry("LDAP://" & strSorceOU_ForMove)
                Try
                    ' Bind to the object to be moved.
                    ' Use the MoveTo property to define the new container you want to move the object to.
                    Using NewOU As New DirectoryEntry("LDAP://" & strNewParentDN)
                        OldOU.MoveTo(NewOU)
                        Call WriteToSQL_Logs(strTable, strPrefix & "Move", strId, strNameOU_ForMove, strSorceOU_ForMove & " was moved from  " & strOldParentDN & " to " & strNewParentDN)
                        strOutputFileMoveOULog.AppendLine(Now.ToString & " ; " & strSorceOU_ForMove & " was moved from  " & strOldParentDN & " to " & strNewParentDN)
                        intCounterMoveOU = intCounterMoveOU + 1
                    End Using
                Catch ex As Exception
                    Call WriteToSQL_Logs(strTable, strPrefix & "Error", strId, strNameOU_ForMove, "Error in moving OU " & strNameOU_ForMove & "; " & strNameOU_ForMove & ex.Message)
                    strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error in moving OU " & strNameOU_ForMove & "; " & strNameOU_ForMove & ex.Message)
                    Return False
                End Try
            End Using
        End If
        Return True
    End Function

    Function MoveExpiredOU(ByVal strSorceOU_ForMove As String, ByVal strTypeOU As String, ByVal strPrefix As String)
        If strSorceOU_ForMove <> String.Empty Then
            Using objEntry As New DirectoryEntry("LDAP://" & strSorceOU_ForMove)
                Dim strNameOU_ForMove As String = objEntry.Properties("name").Value
                Dim strId As String = objEntry.Properties("x121Address").Value
                Dim strTargetOU_ForMove As String = "OU=" & strToday & "_" & strPart & "," & strHRSync
                If CStr(objEntry.Properties("msDS-Approx-Immed-Subordinates").Value) = 0 Then MoveOU(strSorceOU_ForMove, strTargetOU_ForMove, strNameOU_ForMove, strId, strRoot, strPrefix & "_Logs", strPrefix)
            End Using
        End If
    End Function
    Function MoveUser(ByVal strSourceUserDN_ForMove As String, ByVal strTargetOU_ForMove As String, ByVal strFullName_ForMove As String, _
                      ByVal strNewDepartmentID As String, ByVal strUserID As String, ByVal strUserDisplayName As String)
        'strSourceUserDN_ForMove,strTargetOU_ForMove,strFullName_ForMove,strNewDepartmentID


        Dim strCurrentDepartmentID, strSourceOU_ForMove As String
        strSourceOU_ForMove = Right(strSourceUserDN_ForMove, strSourceUserDN_ForMove.Length - strSourceUserDN_ForMove.IndexOf(",OU=") - 1)
        If strSourceOU_ForMove = strTargetOU_ForMove Then Return False

        If strSourceOU_ForMove.IndexOf(strHRSync) = -1 Then
            Using User As New DirectoryEntry("LDAP://" & strSourceUserDN_ForMove)
                strUserID = CStr(User.Properties("employeeID").Value)
                strCurrentDepartmentID = CStr(User.Properties("departmentNumber").Value)

                If CheckOUbyDN(strTargetOU_ForMove, strRootAD) Then

                    Try
                        ' Bind to the object to be moved.
                        'Dim User As New DirectoryEntry("LDAP://" & strSourceUserDN_ForMove)
                        ' Use the MoveTo property to define the new container you want to move the object to.
                        User.MoveTo(New DirectoryEntry("LDAP://" & strTargetOU_ForMove))
                        Call WriteToSQL_Logs("Employee_Logs", "UserMove", strUserID, strFullName_ForMove, "User account " & strFullName_ForMove & " was moved from " & strSourceOU_ForMove & " into " & strTargetOU_ForMove)
                        strOutputFileMoveUserLog.AppendLine(Now.ToString & "; User account " & strFullName_ForMove & " was moved from " & strSourceOU_ForMove & " into " & strTargetOU_ForMove)
                        intCounterMoveUser = intCounterMoveUser + 1
                    Catch ex As Exception
                        Call WriteToSQL_Logs("Employee_Logs", "Error", strUserID, strFullName_ForMove, strSourceUserDN_ForMove & " ; Error in moving user account ; " & strFullName_ForMove & " " & ex.Message)
                        OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & strSourceUserDN_ForMove & " ; Error in moving user account ; " & strFullName_ForMove & " " & ex.Message)
                        Return False
                    End Try
                Else
                    Call WriteToSQL_Logs("Employee_Logs", "Error", strUserID, strFullName_ForMove, " Error in moving user account ; " & strFullName_ForMove & ". Target OU doesnt exist. Check HR Database.")
                    OutputFileErrorUserLog.AppendLine(Now.ToString & " Error in moving user account ; " & strFullName_ForMove & ". Target OU doesnt exist. Check HR Database.")
                    Return False
                End If
            End Using
        End If

    End Function
    Function MoveFiredUserbyID(ByVal strID As String, ByVal strUserDisplayName As String)
        'strSourceUserDN_ForMove,strTargetOU_ForMove,strFullName_ForMove,strNewDepartmentID
        Dim strPath, strTargetOU_ForMove, strSourceUserDN_ForMove As String          ' Binding path.

        strPath = "LDAP://" & strRootAD
        strSourceUserDN_ForMove = GetDN_User_byID(strID, strRootAD)
        strTargetOU_ForMove = "OU=" & strToday & "_" & strPart & "," & strHRSync

        Dim strSourceOU_ForMove, strParentDN As String
        strSourceOU_ForMove = Right(strSourceUserDN_ForMove, strSourceUserDN_ForMove.Length - strSourceUserDN_ForMove.IndexOf(",OU=") - 1)
        If strSourceOU_ForMove = strTargetOU_ForMove Then Return False


        If CheckOUbyDN(strTargetOU_ForMove, strRoot) Then

            strParentDN = Right(strSourceUserDN_ForMove, Len(strSourceUserDN_ForMove) - InStr(strSourceUserDN_ForMove, ",OU="))
            Using deUser As New DirectoryEntry("LDAP://" & strSourceUserDN_ForMove)
                Try
                    ' Bind to the object to be moved.
                    Dim val As Integer = CInt(deUser.Properties("userAccountControl").Value)
                    deUser.Properties("userAccountControl").Value = val Or &H2
                    deUser.Properties("msExchHideFromAddressLists").Value = "TRUE"
                    deUser.CommitChanges()
                    Call WriteToSQL_Logs("Employee_Logs", "MoveFiredUser", strID, strUserDisplayName, "User account " & strUserDisplayName & " was disabled.")
                    OutputFileMoveFiredLog.AppendLine(Now.ToString & " User account " & strUserDisplayName & " was disabled.")
                Catch ex As Exception
                    Call WriteToSQL_Logs("Employee_Logs", "Error", strID, strUserDisplayName, " Error in disabling user account ; " & strUserDisplayName & " " & ex.Message)
                    OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & strUserDisplayName & " ; Error in disabling user account ; " & strUserDisplayName & " " & ex.Message)
                End Try
                ClearProperty(strSourceUserDN_ForMove, "manager", strID, "Employee_logs", "User")
                Try
                    deUser.MoveTo(New DirectoryEntry("LDAP://" & strTargetOU_ForMove))
                    deUser.CommitChanges()
                    Call WriteToSQL_Logs("Employee_Logs", "MoveFiredUser", strID, strUserDisplayName, "User account " & strUserDisplayName & " was moved " & strSourceOU_ForMove & " в OU=" & strToday & "_" & strPart & "," & strHRSync)
                    OutputFileMoveFiredLog.AppendLine(Now.ToString & " User account " & strUserDisplayName & " was moved " & strSourceOU_ForMove & " в OU=" & strToday & "_" & strPart & "," & strHRSync)
                    intCounterMoveFiredUser = intCounterMoveFiredUser + 1
                Catch ex As Exception
                    Call WriteToSQL_Logs("Employee_Logs", "Error", strID, strUserDisplayName, " Error in moving user account ; " & strUserDisplayName & " " & ex.Message)
                    OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & strUserDisplayName & " ; Error in moving user account ; " & strUserDisplayName & " " & ex.Message)
                End Try
            End Using
        Else
            Call WriteToSQL_Logs("Employee_Logs", "Error", strID, strUserDisplayName, "Error in moving user account  " & strUserDisplayName & ". Target OU doesnt exist.")
            OutputFileErrorUserLog.AppendLine(Now.ToString & "; Error in moving user account  " & strUserDisplayName & ". . Target OU doesnt exist.")

        End If

    End Function


    Public Sub RenameProperty(ByVal strDN_IN As String, ByVal PropertyName As String, ByVal PropertyValue As String, ByVal strId As String, ByVal strTable As String, ByVal strPrefix As String)
        ' Use the InvokeSet property to define the new value.
        Dim strOldValue As String
        Using de As New DirectoryEntry("LDAP://" & strDN_IN)

            Try
                If de.Properties.Contains(PropertyName) Then
                    strOldValue = de.Properties(PropertyName).Value
                Else
                    strOldValue = String.Empty
                End If

                If strOldValue <> PropertyValue Then
                    de.Rename(PropertyName & "=" & PropertyValue)
                End If
                de.CommitChanges()
                Call WriteToSQL_Logs(strTable, strPrefix & "RenameLog", PropertyName, strId, PropertyName & " was renamed from " & strOldValue & " to " & PropertyValue)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileRenameOULog.AppendLine(Now.ToString & " ; OU " & strId & " ; " & PropertyName & " was renamed from " & strOldValue & " to " & PropertyValue)
                    Case "User"
                        strOutputFileRenameUserLog.AppendLine(Now.ToString & " ; User " & strId & " ; " & PropertyName & " was renamed from " & strOldValue & " to " & PropertyValue)
                End Select
            Catch ex As Exception
                Call WriteToSQL_Logs(strTable, strPrefix & "Error", PropertyName, strId, "Error in renaming " & PropertyName & " from " & strOldValue & " to " & PropertyValue & " " & ex.Message)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; OU " & strId & " ; Error in renaming" & PropertyName & " from " & strOldValue & " to " & PropertyValue & " " & ex.Message)
                    Case "User"
                        strOutputFileErrorUserLog.AppendLine(Now.ToString & " ; User " & strId & " ; Error in renaming" & PropertyName & " from " & strOldValue & " to " & PropertyValue & " " & ex.Message)
                End Select
            End Try
        End Using
    End Sub
    Public Sub CheckOUbyName(ByVal strDPDN_ForCheck As String, ByVal intCounter As Integer, ByVal strTable As String, strPrefix As String)
        'sb.AppendLine("Start check OU: {0}", strDepartmentName_ForCheck)

        Dim strDepartmentID_ForCheck As String = intDPDepartmentID(intCounter)
        Dim strDepartmentName_ForCheck As String = strDPDepartmentName(intCounter)
        Dim strFullDepartmentName_ForCheck As String = strDPFullDepartmentName(intCounter)
        Dim strDateValid_ForCheck As String = strDPDateValid(intCounter)
        Dim strManagedBy_ForCheck As Integer = strDPManagedBy(intCounter)
        Dim strRegion_ForCheck As String = strDPRegion(intCounter)
        Dim strCity_ForCheck As String = strDPCity(intCounter)
        Dim strStreet_ForCheck As String = strDPStreet(intCounter)
        Dim strPostalCode_ForCheck As String = strDPPostalCode(intCounter)
        Dim strCountry_ForCheck As String = strDPCountry(intCounter)
        Dim strCountryCode_ForCheck As String = strDPCountryCode(intCounter)
        Dim strCountryAbr_ForCheck As String = strDPCountryAbr(intCounter)

        ' Bind to the object to be moved.
        Using de As New DirectoryEntry("LDAP://" & strDPDN_ForCheck)
            de.RefreshCache()
            If de.Properties("x121Address").Value <> strDepartmentID_ForCheck Then
                'sb.AppendLine("Start Rename")
                UpdateProperty(strDPDN_ForCheck, "x121Address", strDepartmentID_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("description").Value <> strFullDepartmentName_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "description", strFullDepartmentName_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("adminDescription").Value <> strDateValid_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "adminDescription", strDateValid_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("st").Value <> strRegion_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "st", strRegion_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("l").Value <> strCity_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "l", strCity_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If
            If de.Properties("street").Value <> strStreet_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "street", strStreet_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("postalCode").Value <> strPostalCode_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "postalCode", strPostalCode_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("co").Value <> strCountry_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "co", strCountry_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("countryCode").Value <> strCountryCode_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "countryCode", strCountryCode_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("from").Value <> strCountryAbr Then
                UpdateProperty(strDPDN_ForCheck, "from", strCountryAbr_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            Dim strManagerDN As String = GetDN_User_byID(CStr(strManagedBy_ForCheck), strRootAD)
            If de.Properties("managedBy").Value <> strManagerDN Then
                UpdateProperty(strDPDN_ForCheck, "managedBy", strManagerDN, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If
        End Using
    End Sub


    Public Sub CheckOU(ByVal strDPDN_ForCheck As String, ByVal intCounter As Integer, ByVal strTypeOU_ForCheck As String, ByVal strTable As String, strPrefix As String)
        Dim strDepartmentID_ForCheck As String = strTypeOU_ForCheck & CStr(intDPDepartmentID(intCounter))
        Dim strDepartmentName_ForCheck As String = strDPDepartmentName(intCounter)
        Dim strFullDepartmentName_ForCheck As String = strDPFullDepartmentName(intCounter)
        Dim strDateValid_ForCheck As String = strDPDateValid(intCounter)
        Dim strManagedBy_ForCheck As Integer = strDPManagedBy(intCounter)
        Dim strRegion_ForCheck As String = strDPRegion(intCounter)
        Dim strCity_ForCheck As String = strDPCity(intCounter)
        Dim strStreet_ForCheck As String = strDPStreet(intCounter)
        Dim strPostalCode_ForCheck As String = strDPPostalCode(intCounter)
        Dim strCountry_ForCheck As String = strDPCountry(intCounter)
        Dim strCountryCode_ForCheck As String = strDPCountryCode(intCounter)
        Dim strCountryAbr_ForCheck As String = strDPCountryAbr(intCounter)
        ' Construct the binding string.

        Using de As New DirectoryEntry("LDAP://" & strDPDN_ForCheck)
            de.RefreshCache()

            If de.Properties("x121Address").Value <> strDepartmentID_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "x121Address", strDepartmentID_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("description").Value <> strFullDepartmentName_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "description", strFullDepartmentName_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("adminDescription").Value <> strDateValid_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "adminDescription", strDateValid_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("st").Value <> strRegion_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "st", strRegion_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("l").Value <> strCity_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "l", strCity_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If
            If de.Properties("street").Value <> strStreet_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "street", strStreet_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("postalCode").Value <> strPostalCode_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "postalCode", strPostalCode_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("co").Value <> strCountry_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "co", strCountry_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("countryCode").Value <> strCountryCode_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "countryCode", strCountryCode_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            If de.Properties("c").Value <> strCountryAbr_ForCheck Then
                UpdateProperty(strDPDN_ForCheck, "c", strCountryAbr_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If

            Dim strManagerDN As String = GetDN_User_byID(CStr(strManagedBy_ForCheck), strRootAD)
            If de.Properties("managedBy").Value <> strManagerDN Then
                Select Case IsManagerActive(strManagedBy_ForCheck)
                    Case "fired"
                        ClearProperty(strDPDN_ForCheck, "managedBy", strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
                    Case "hired"
                        UpdateProperty(strDPDN_ForCheck, "managedBy", strManagerDN, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
                        intCounterUpdateOU = intCounterUpdateOU + 1
                    Case "not found"
                        ClearProperty(strDPDN_ForCheck, "managedBy", strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
                End Select
            End If

            If de.Properties("ou").Value <> strDepartmentName_ForCheck Then
                RenameProperty(strDPDN_ForCheck, "ou", strDepartmentName_ForCheck, strDepartmentID_ForCheck, strPrefix & "_Logs", strPrefix)
            End If
        End Using
    End Sub

    Public Function GetDN_User_byID(ByVal strID As String, ByVal strRootIn As String) As String
        If strID = String.Empty Then Return String.Empty
        ' Binding object.
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.

        ' Construct the binding string.
        strPath = "LDAP://" & strRootAD
        strFilter = "(&(objectCategory=person)(objectClass=user)(employeeID=" & strID & "))"

        ' Get AD LDS object.
        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.PropertiesToLoad.Add("distinguishedName")
                objSearchADAM.SearchScope = SearchScope.Subtree
                ' Enumerate filtered objects.
                Try
                    Dim objResult = objSearchADAM.FindOne()
                    If Not IsNothing(objResult) Then
                        Return CStr(objResult.Properties("distinguishedName")(0))
                    Else
                        Return String.Empty
                    End If

                Catch ex As Exception

                End Try
            End Using
        End Using
    End Function
    Public Function GetDN_User_byNameWithoutID(ByVal strName As String, ByVal strRootIn As String) As String
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.

        ' Construct the binding string.
        strPath = "LDAP://" & strRootAD
        'sb.AppendLine("Bind to: {0}", strPath)

        ' Specify filter.
        strFilter = "(&(objectCategory=person)(objectClass=user)(CN=" & strName & "' and !employeeID=*))"
        'sb.AppendLine("Filter:  {0}", strFilter)

        ' Get AD LDS object.
        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            Using objSearchADAM = New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.PropertiesToLoad.Add("distinguishedName")
                objSearchADAM.SearchScope = SearchScope.Subtree
                ' Enumerate filtered objects.
                Try
                    Dim objResult = objSearchADAM.FindOne()
                    If Not IsNothing(objResult) Then
                        GetDN_User_byNameWithoutID = CStr(objResult.Properties("distinguishedName")(0))
                    Else
                        GetDN_User_byNameWithoutID = String.Empty
                    End If
                Catch ex As Exception

                End Try
            End Using
        End Using
    End Function





    Public Sub ClearProperty(ByVal strDN_IN As String, ByVal strPropertyName As String, ByVal strId As String, ByVal strTable As String, ByVal strPrefix As String)
        Dim strOldValue As String = String.Empty
        Using de As New DirectoryEntry("LDAP://" & strDN_IN)
            de.RefreshCache()
            Try
                If de.Properties.Contains(strPropertyName) Then
                    'Clear the properties value  
                    strOldValue = de.Properties(strPropertyName).Value
                    de.Properties(strPropertyName).Clear()
                End If
                de.CommitChanges()
                Call WriteToSQL_Logs(strTable, "Update", strId, strPropertyName, "Value " & strPropertyName & " was cleared from " & strOldValue)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileUpdateOULog.AppendLine(Now.ToString & " ; OU  with DepartmentID " & strId & " ; Value " & strPropertyName & " was cleared from " & strOldValue)
                    Case "User"
                        strOutputFileUpdateUserLog.AppendLine(Now.ToString & " ; User with EmployeeID " & strId & " ; Value " & strPropertyName & " was cleared from " & strOldValue)
                End Select
            Catch ex As Exception
                Call WriteToSQL_Logs(strTable, "Error", strId, strPropertyName, "Error in clearing " & strPropertyName & " from " & strOldValue)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; OU with DepartmentID " & strId & " ; Error in clearing  " & strPropertyName & " from " & strOldValue)
                    Case "User"
                        strOutputFileErrorUserLog.AppendLine(Now.ToString & " ; User with EmployeeID " & strId & " ; Error in clearing  " & strPropertyName & " from " & strOldValue)
                End Select
            End Try
        End Using
    End Sub

    Public Sub UpdateProperty(ByVal strDN_IN As String, ByVal strPropertyName As String, ByVal PropertyValue As String, ByVal strId As String, ByVal strTable As String, ByVal strPrefix As String)
        ' Use the InvokeSet property to define the new value.
        Dim strOldValue As String
        Using de As New DirectoryEntry("LDAP://" & strDN_IN)
            de.RefreshCache()
            Try
                If Not PropertyValue Is Nothing Then
                    'Check to see if the DirectoryEntry contains this property already  
                    If de.Properties.Contains(strPropertyName) Then   'The DE contains this property  
                        'Update the properties value  
                        strOldValue = de.Properties(strPropertyName).Value
                        de.Properties(strPropertyName)(0) = PropertyValue
                    Else    'Property doesnt exist  
                        'Add the property and set it's value  
                        strOldValue = "empty"
                        de.Properties(strPropertyName).Add(PropertyValue)
                    End If
                End If
                de.CommitChanges()
                Call WriteToSQL_Logs(strTable, strPrefix & "UpdateLog", strId, strPropertyName, "Value " & strPropertyName & " was updated from " & strOldValue & " to " & PropertyValue)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileUpdateOULog.AppendLine(Now.ToString & " ; OU with DepartmentID " & strId & " ; Value " & strPropertyName & " was updated from " & strOldValue & " to " & PropertyValue)
                    Case "User"
                        strOutputFileUpdateUserLog.AppendLine(Now.ToString & " ; User with EmployeeID " & strId & " ; Value " & strPropertyName & " was updated from " & strOldValue & " to " & PropertyValue)
                End Select
            Catch ex As Exception
                Call WriteToSQL_Logs(strTable, strPrefix & "Error", strId, strPropertyName, "Error in updating " & strPropertyName & " from " & strOldValue & " to " & PropertyValue)
                Select Case strPrefix
                    Case "OU"
                        strOutputFileErrorOULog.AppendLine(Now.ToString & " ; OU with DepartmentID " & strId & " ; Error in updating  " & strPropertyName & " from " & strOldValue & " to " & PropertyValue)
                    Case "User"
                        strOutputFileErrorUserLog.AppendLine(Now.ToString & " ; User with EmployeeID " & strId & " ; Error in updating  " & strPropertyName & " from " & strOldValue & " to " & PropertyValue)
                End Select
            End Try
        End Using
    End Sub
    Function MoveEmptyNonHROU(ByVal strRootIn_ForMove As String, ByVal strTableIn As String, ByVal strPrefixIn As String)
        Dim objEntry As DirectoryEntry                  ' DirectoryEntry in Results.
        Dim objSearchResults As SearchResultCollection  ' Results collection.
        Dim strFilter As String                         ' Filter to select objects.
        Dim strPath As String                           ' Binding path.
        Dim strDPDN_MoveNonHROU, strNameOU As String
        Dim strTargetOU_ForMove, strSorceOU_ForMove As String

        ' Construct the binding string.
        strPath = "LDAP://" & strRootIn_ForMove

        ' Specify filter.
        strFilter = "(&(&(ou>="")(objectCategory=organizationalUnit)(objectClass=organizationalUnit)(!x121Address=*)))"

        ' Get AD LDS object.

        Using de As New DirectoryEntry(strPath)
            de.RefreshCache()
            ' Get search object,
            '  specify filter and scope,
            '  perform search.
            Using objSearchADAM As New DirectorySearcher(de)
                objSearchADAM.Filter = strFilter
                objSearchADAM.SearchScope = SearchScope.Subtree
                objSearchResults = objSearchADAM.FindAll()
                ' Enumerate filtered objects.
                Try
                    If objSearchResults.Count <> 0 Then
                        Dim objResult As SearchResult
                        For Each objResult In objSearchResults
                            objEntry = objResult.GetDirectoryEntry()

                            If CStr(objEntry.Properties("msDS-Approx-Immed-Subordinates").Value) = 0 Then
                                strDPDN_MoveNonHROU = CStr(objEntry.Properties("distinguishedName").Value)
                                strNameOU = CStr(objEntry.Properties("name").Value)
                                Call WriteToSQL_Logs(strTableIn, strPrefixIn & "Move", "XXXXX", strNameOU, strDPDN_MoveNonHROU & "Field department number (x121Address) is empty.OU is empty. Moving to " & strHRSync)
                                strTargetOU_ForMove = "OU=" & strToday & "_" & strPart & "," & strHRSync
                                strSorceOU_ForMove = strDPDN_MoveNonHROU
                                'Call UnprotectObject(strSorceOU_ForMove)
                                If CheckOUbyDN(strTargetOU_ForMove, strRoot) Then
                                    MoveOU(strSorceOU_ForMove, strTargetOU_ForMove, strNameOU, "XXXXX", strRoot, strTableIn, strPrefixIn)
                                    intCounterNonHRMoveOU = intCounterNonHRMoveOU + 1
                                End If
                            Else
                            End If
                        Next objResult

                    Else

                    End If
                Catch ex As Exception

                End Try
            End Using
        End Using
    End Function
    Public Sub OU_Management(ByVal strRootIn As String, ByVal strTypeOU As String, ByVal strPrefix As String)
        intCounterCreateOU = 0
        intCounterMoveOU = 0
        intCounterNonHRMoveOU = 0
        intCounterRenameOU = 0
        intCounterUpdateOU = 0
        intCurrentOUCounter = 0
        'ProtectObject(strRootIn, strRootIn)
        Do While intCurrentOUCounter <= intQuantityLines_DP

            strDNCurrentOU = GetDN_OU_byID(strTypeOU & intDPDepartmentID(intCurrentOUCounter), strRootIn)

            If strDPDateValid(intCurrentOUCounter) > strToday Then

                If strDNCurrentOU <> String.Empty Then

                    strDNParentOU = GetDN_OU_byID(strTypeOU & intDPParentDepartmentID(intCurrentOUCounter), strRootIn)
                    strDNCurrentParentOU = Right(strDNCurrentOU, strDNCurrentOU.Length - strDNCurrentOU.IndexOf(",") - 1)
                    If strDNCurrentParentOU <> strDNParentOU Then
                        Call MoveOU(strDNCurrentOU, strDNParentOU, strDPDepartmentName(intCurrentOUCounter), strTypeOU & intDPDepartmentID(intCurrentOUCounter), strRootIn, strPrefix & "_Logs", strPrefix)
                    End If
                    strDNCurrentOU = GetDN_OU_byID(strTypeOU & intDPDepartmentID(intCurrentOUCounter), strRootIn)
                    Call CheckOU(strDNCurrentOU, intCurrentOUCounter, strTypeOU, strPrefix & "_Logs", strPrefix)
                Else
                    Call CreateOU(intCurrentOUCounter, strRootIn, strTypeOU, strPrefix & "_Logs", strPrefix)

                End If      ' End strDNCurrentOU <> String.Empty
            Else  ' strDPDateValid(intCurrentOUCounter) <= strToday
                If strDNCurrentOU <> String.Empty Then
                    Call CheckOU(strDNCurrentOU, intCurrentOUCounter, strTypeOU, strPrefix & "_Logs", strPrefix)
                    MoveExpiredOU(strDNCurrentOU, strTypeOU, strPrefix)
                End If
            End If 'sstrDPDateValid(intCurrentOUCounter) > strToday
            ' -----------------------------------------------------------------------------------------------------------------
            ' Go to next record
            ' -----------------------------------------------------------------------------------------------------------------
            intCurrentOUCounter = intCurrentOUCounter + 1
        Loop
        MoveEmptyNonHROU(strRootIn, strPrefix & "_Logs", strPrefix)
        If intCounterCreateOU <> 0 Then
            Console.WriteLine(" Created " & intCounterCreateOU & " OU accounts.")
            strOutputFileOULog.AppendLine(DateTime.Now.ToString & "; Created " & intCounterCreateOU & " OU.")
        End If
        If intCounterUpdateOU <> 0 Then
            strOutputFileOULog.AppendLine(DateTime.Now.ToString & "; Updated " & intCounterUpdateOU & " OU.")
        End If
        If intCounterRenameOU <> 0 Then
            strOutputFileOULog.AppendLine(DateTime.Now.ToString & "; Renamed " & intCounterRenameOU & " OU.")
        End If
        If intCounterMoveOU <> 0 Then
            strOutputFileOULog.AppendLine(DateTime.Now.ToString & "; Moved " & intCounterMoveOU & " OU.")
        End If
        If intCounterNonHRMoveOU <> 0 Then
            strOutputFileOULog.AppendLine(DateTime.Now.ToString & "; Moved " & intCounterNonHRMoveOU & " OU, that has no records in HR.")
        End If
        Using outfile As New System.IO.StreamWriter(strCommonLogOUPath + "CommonOULog.txt", True)
            outfile.Write(strOutputFileOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strCommonLogOUPath + "CreateOULog.txt", True)
            outfile.Write(strOutputFileCreateOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strCommonLogOUPath + "UpdateOULog.txt", True)
            outfile.Write(strOutputFileUpdateOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strCommonLogOUPath + "RenameOULog.txt", True)
            outfile.Write(strOutputFileRenameOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strCommonLogOUPath + "MoveOULog.txt", True)
            outfile.Write(strOutputFileMoveOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + "CommonOULog.txt", True)
            outfile.Write(strOutputFileOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + strToday + "CommonOULog.txt", True)
            outfile.Write(strOutputFileOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + strToday + "CreateOULog.txt", True)
            outfile.Write(strOutputFileCreateOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + strToday + "UpdateOULog.txt", True)
            outfile.Write(strOutputFileUpdateOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + strToday + "RenameOULog.txt", True)
            outfile.Write(strOutputFileRenameOULog)
        End Using
        Using outfile As New System.IO.StreamWriter(strTodayLogOUPath + strToday + "MoveOULog.txt", True)
            outfile.Write(strOutputFileMoveOULog)
        End Using
        Console.WriteLine("Created OU {0}:{1}", strTypeOU, intCounterCreateOU)
    End Sub




    Function FindUserSAM(ByVal strSAM As String) As Boolean
        Using ctx As New PrincipalContext(ContextType.Domain)
            Using userPrincipal As UserPrincipal = userPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, strSAM)
                If Not IsNothing(userPrincipal) Then
                    Return True
                Else
                    Return False
                End If
            End Using
        End Using  '
    End Function
    Function FindUserCN(ByVal strCN As String) As Boolean
        Using ctx As New PrincipalContext(ContextType.Domain)
            Using userPrincipal As UserPrincipal = userPrincipal.FindByIdentity(ctx, IdentityType.Name, strCN)
                If Not IsNothing(userPrincipal) Then
                    Return True
                Else
                    Return False
                End If
            End Using
        End Using   '
    End Function



    Sub User_Management()


        Dim strCurrentFullName, strDNameTargetOU As String
        '------------------------------------------------------------------------------------------------------------------
        ' Обработка входных данных
        'WScript.Quit 
        intCurrentEmployeeCounter = 0
        Do While intCurrentEmployeeCounter <= intQuantityLines_User

            strCurrentDN = String.Empty
            strCurrentFullName = strFullName(intCurrentEmployeeCounter)
            If strDateValid(intCurrentEmployeeCounter) < strToday Then
                If GetDN_User_byID(strEmployeeID(intCurrentEmployeeCounter), strRootAD) <> String.Empty Then MoveFiredUserbyID(strEmployeeID(intCurrentEmployeeCounter), strFullName(intCurrentEmployeeCounter))
            Else

                'We are looking for user in AD by ID
                strCurrentDN = GetDN_User_byID(strEmployeeID(intCurrentEmployeeCounter), strRootAD)
                '----------------------------------
                If strCurrentDN = String.Empty Then
                    '----------------------------------
                    ' User not found
                    ' We are looking for user in AD by name without ID
                    '----------------------------------
                    strCurrentDN = GetDN_User_byNameWithoutID(strCurrentFullName, strRootAD)
                    ' 
                    If strCurrentDN <> String.Empty Then
                        '-------------------------------------------------------------------------------------
                        ' We found the account without EmployeeID 
                        ' It was created by hand
                        '-------------------------------------------------------------------------------------
                        If Not (UserHaveID(strCurrentDN)) Then ' 
                            '-------------------------------------------------------------------------------------
                            ' Мы нашли учетную запись с полным совпадением фио, но не имеющую ID и проверяем правильность заполнения атрибутов учетной записи по 7 полям"
                            '-------------------------------------------------------------------------------------
                            Call CheckUser(intCurrentEmployeeCounter)

                        Else
                            '-------------------------------------------------------------------------------------
                            Call CreateUser(intCurrentEmployeeCounter)
                        End If
                    Else
                        '-------------------------------------------------------------------------------------
                        'We did not find a user account and create a new one.
                        '-------------------------------------------------------------------------------------
                        Call CreateUser(intCurrentEmployeeCounter)
                    End If
                Else
                    '----------------------------------
                    ' We found the account with EmployeeID 
                    '----------------------------------
                    strDNameTargetOU = GetDN_OU_byID(strDepartmentID(intCurrentEmployeeCounter), strRoot)
                    If Right(strCurrentDN, Len(strCurrentDN) - InStr(strCurrentDN, ",")) <> strDNameTargetOU Then
                        Call MoveUser(strCurrentDN, strDNameTargetOU, strCurrentFullName, strDepartmentID(intCurrentEmployeeCounter), strEmployeeID(intCurrentEmployeeCounter), strFullName(intCurrentEmployeeCounter))
                        Call CheckUser(intCurrentEmployeeCounter)
                    Else
                        Call CheckUser(intCurrentEmployeeCounter)
                    End If
                End If

            End If


            intCurrentEmployeeCounter = intCurrentEmployeeCounter + 1

        Loop
        If intCounterCreateUser <> 0 Then
            Console.WriteLine(" Created " & intCounterCreateUser & " user accounts.")
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Created " & intCounterCreateUser & " user accounts.")
        End If
        If intCounterUpdateUser <> 0 Then
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Updated " & intCounterUpdateUser & " user accounts.")
        End If
        If intCounterRenameUser <> 0 Then
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Renamed " & intCounterRenameUser & " user accounts.")
        End If
        If intCounterMoveUser <> 0 Then
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Moved " & intCounterMoveUser & " user accounts.")
        End If
        If intCounterMoveFiredUser <> 0 Then
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Moved " & intCounterMoveFiredUser & " fired user accounts.")
        End If
        If intCounterNonHRMoveUser <> 0 Then
            strOutputFileUserLog.AppendLine(DateTime.Now.ToString & "; Moved " & intCounterNonHRMoveUser & " user accounts, that has no records in HR.")
        End If
        Using outfile As New StreamWriter(strCommonLogUserPath + "CommonUserLog.txt", True)
            outfile.Write(strOutputFileUserLog)
        End Using
        Using outfile As New StreamWriter(strCommonLogUserPath + "CreateUserLog.txt", True)
            outfile.Write(strOutputFileCreateUserLog)
        End Using
        Using outfile As New StreamWriter(strCommonLogUserPath + "UpdateUserLog.txt", True)
            outfile.Write(strOutputFileUpdateUserLog)
        End Using
        Using outfile As New StreamWriter(strCommonLogUserPath + "RenameUserLog.txt", True)
            outfile.Write(strOutputFileRenameUserLog)
        End Using
        Using outfile As New StreamWriter(strCommonLogUserPath + "MoveUserLog.txt", True)
            outfile.Write(strOutputFileMoveUserLog)
        End Using
        Using outfile As New StreamWriter(strTodayLogUserPath + strToday + "CommonUserLog.txt", True)
            outfile.Write(strOutputFileUserLog)
        End Using
        Using outfile As New StreamWriter(strTodayLogUserPath + strToday + "CreateUserLog.txt", True)
            outfile.Write(strOutputFileCreateUserLog)
        End Using
        Using outfile As New StreamWriter(strTodayLogUserPath + strToday + "UpdateUserLog.txt", True)
            outfile.Write(strOutputFileUpdateUserLog)
        End Using
        Using outfile As New StreamWriter(strTodayLogUserPath + strToday + "RenameUserLog.txt", True)
            outfile.Write(strOutputFileRenameUserLog)
        End Using
        Using outfile As New StreamWriter(strTodayLogUserPath + strToday + "MoveUserLog.txt", True)
            outfile.Write(strOutputFileMoveUserLog)
        End Using
    End Sub


    Function GetDataUsersFromSQL()
        Dim counter As Integer
        Dim SQLStr As String
        Dim ConnString As String
        Using SQLConn As New SqlConnection() 'The SQL Connection
            Using SQLCmd As New SqlCommand() 'The SQL Command
                'Using SQLdr As SqlDataReader

                ConnString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" & DBName & ";Data Source=" & DBServer & ";"


                SQLConn.ConnectionString = ConnString 'Set the Connection Str
                SQLConn.Open() 'Open the connection
                SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
                SQLStr = " SELECT  [employee_id] ,[first_name],[last_name],[phone_int] ,[job_title],[manager_id] ,[department_id] ,[department_name],[date_valid] ," & _
                        "[street_address] ,[postal_code] ,[city] ,[state_province] ,[country_name] ,[country_code] ,[country_abr] " & _
                        " From [Employees]  ORDER BY [department_id]"
                SQLCmd.CommandText = SQLStr 'Sets the SQL String
                Using SQLdr As SqlDataReader = SQLCmd.ExecuteReader 'Gets Data

                    While SQLdr.Read() 'While Data is Present        

                        ReDim Preserve strEmployeeID(counter)
                        ReDim Preserve strEmployeeNumber(counter)
                        ReDim Preserve strLastName(counter)
                        ReDim Preserve strGivenName(counter)
                        ReDim Preserve strMiddleName(counter)
                        ReDim Preserve strBirthDate(counter)
                        ReDim Preserve strTitleID(counter)
                        ReDim Preserve strJobTitle(counter)
                        ReDim Preserve strFullJobTitle(counter)
                        ReDim Preserve strEmployeeNumber(counter)
                        ReDim Preserve strDepartmentID(counter)
                        ReDim Preserve strDepartment(counter)
                        ReDim Preserve strFullDepartmentName(counter)
                        ReDim Preserve strManagerID(counter)
                        ReDim Preserve strDateValid(counter)
                        ReDim Preserve strFullName(counter)
                        ReDim Preserve strEmployeeType(counter)
                        ReDim Preserve strRegion(counter)
                        ReDim Preserve strCountry(counter)
                        ReDim Preserve strCountryCode(counter)
                        ReDim Preserve strCountryAbr(counter)
                        ReDim Preserve strCity(counter)
                        ReDim Preserve strStreet(counter)
                        ReDim Preserve strPostalCode(counter)
                        ReDim Preserve strCompany(counter)
                        ReDim Preserve strPhone(counter)
                        ' 	обнуляем данные перед считыванием
                        strCompany(counter) = String.Empty
                        strEmployeeID(counter) = String.Empty
                        strEmployeeNumber(counter) = String.Empty
                        strLastName(counter) = String.Empty
                        strGivenName(counter) = String.Empty
                        strMiddleName(counter) = String.Empty
                        strBirthDate(counter) = String.Empty
                        strTitleID(counter) = String.Empty
                        strJobTitle(counter) = String.Empty
                        strFullJobTitle(counter) = String.Empty
                        strEmployeeNumber(counter) = String.Empty
                        strEmployeeType(counter) = String.Empty
                        strDepartmentID(counter) = String.Empty
                        strDepartment(counter) = String.Empty
                        strFullDepartmentName(counter) = String.Empty
                        strManagerID(counter) = String.Empty
                        strDateValid(counter) = String.Empty
                        strFullName(counter) = String.Empty
                        strRegion(counter) = String.Empty
                        strCountry(counter) = String.Empty
                        strCountryCode(counter) = String.Empty
                        strCountryAbr(counter) = String.Empty
                        strCity(counter) = String.Empty
                        strStreet(counter) = String.Empty
                        strPostalCode(counter) = String.Empty
                        strPhone(counter) = String.Empty
                        strCompany(counter) = "Contoso ltd."
                        '	считывание массива
                        strEmployeeID(counter) = Trim(SQLdr("employee_id").ToString)
                        strLastName(counter) = Trim(CStr(SQLdr("last_name")))
                        strGivenName(counter) = Trim(CStr(SQLdr("first_name")))
                        strJobTitle(counter) = CStr(SQLdr("job_title"))
                        strDepartmentID(counter) = Trim(SQLdr("department_id").ToString)
                        strDepartment(counter) = CStr(SQLdr("department_name"))
                        If Not IsDBNull(SQLdr("manager_id")) Then
                            strManagerID(counter) = Trim(CStr(SQLdr("manager_id")))
                        End If
                        strDateValid(counter) = CStr(SQLdr("date_valid"))
                        strPhone(counter) = CStr(SQLdr("phone_int"))
                        strRegion(counter) = CStr(SQLdr("state_province"))
                        strCountry(counter) = CStr(SQLdr("country_name"))
                        strCountryCode(counter) = CStr(SQLdr("country_code"))
                        strCountryAbr(counter) = CStr(SQLdr("country_abr"))
                        strCity(counter) = CStr(SQLdr("city"))
                        strStreet(counter) = CStr(SQLdr("street_address"))
                        strPostalCode(counter) = CStr(SQLdr("postal_code"))
                        strFullName(counter) = strGivenName(counter) & " " & strLastName(counter)
                        counter = counter + 1
                    End While
                End Using
                'SQLdr.Close() 'Close the SQLDataReader        
            End Using
        End Using
        'Close the connection
        intQuantityLines_User = counter - 1
        Console.WriteLine(intQuantityLines_User)
    End Function
    Function UserHaveID(ByVal strDN As String)
        Dim objEntry As DirectoryEntry                  ' DirectoryEntry in Results.
        Dim strPath As String                           ' Binding path.        

        ' Construct the binding string.
        strPath = "LDAP://" & strDN

        ' Get AD LDS object.
        Try
            objEntry = New DirectoryEntry("LDAP://" & strDN)
            objEntry.RefreshCache()
            If Not String.IsNullOrEmpty(CStr(objEntry.Properties("EmployeeID").Value)) Then
                UserHaveID = True
            Else
                UserHaveID = False
            End If
            objEntry.Close()
        Catch ex As Exception
            objEntry.Close()
            Return False
        End Try

    End Function
    Function CreateSAM(ByVal strLastName_ForCreate As String, ByVal strGivenName_ForCreate As String, ByVal strMiddleName_ForCreate As String) As String
        Dim strForstrsAMAccountName_ForCreate, strsAMAccountName_ForCreate As String
        strForstrsAMAccountName_ForCreate = strLastName_ForCreate & "." & Left(strGivenName_ForCreate, 1)
        If strMiddleName_ForCreate <> String.Empty Then strForstrsAMAccountName_ForCreate = strForstrsAMAccountName_ForCreate + Left(strMiddleName_ForCreate, 1)
        strsAMAccountName_ForCreate = strForstrsAMAccountName_ForCreate
        If Not FindUserSAM(strsAMAccountName_ForCreate) Then
            CreateSAM = strsAMAccountName_ForCreate
        Else
            strForstrsAMAccountName_ForCreate = strLastName_ForCreate & "." & Left(strGivenName_ForCreate, 1) + Left(strMiddleName_ForCreate, 2)
            strsAMAccountName_ForCreate = strForstrsAMAccountName_ForCreate
            If Not FindUserSAM(strsAMAccountName_ForCreate) Then
                CreateSAM = strsAMAccountName_ForCreate
            Else
                strForstrsAMAccountName_ForCreate = strLastName_ForCreate & "." & Left(strGivenName_ForCreate, 2) + Left(strMiddleName_ForCreate, 1)
                strsAMAccountName_ForCreate = strForstrsAMAccountName_ForCreate
                If Not FindUserSAM(strsAMAccountName_ForCreate) Then
                    CreateSAM = strsAMAccountName_ForCreate
                Else
                    strForstrsAMAccountName_ForCreate = strLastName_ForCreate & "." & Left(strGivenName_ForCreate, 2) + Left(strMiddleName_ForCreate, 2)
                    strsAMAccountName_ForCreate = strForstrsAMAccountName_ForCreate
                    CreateSAM = strsAMAccountName_ForCreate
                End If
            End If
        End If
    End Function

    Function CreateUser(ByVal intCounterForCreate As Integer) As Boolean
        Dim strFullName_ForCreate As String = strFullName(intCounterForCreate)
        Dim strLastName_ForCreate As String = strLastName(intCounterForCreate)
        Dim strGivenName_ForCreate As String = strGivenName(intCounterForCreate)
        Dim strMiddleName_ForCreate As String = strMiddleName(intCounterForCreate)
        Dim strEmployeeID_ForCreate As String = strEmployeeID(intCounterForCreate)
        Dim strEmployeeNumber_ForCreate As String = strEmployeeNumber(intCounterForCreate)
        Dim strEmployeeType_ForCreate As String = strEmployeeType(intCounterForCreate)
        Dim strBirthDate_ForCreate As String = strBirthDate(intCounterForCreate)
        Dim strJobTitle_ForCreate As String = strJobTitle(intCounterForCreate)
        Dim strFullJobTitle_ForCreate As String = strFullJobTitle(intCounterForCreate)
        Dim strDepartmentID_ForCreate As String = strDepartmentID(intCounterForCreate)
        Dim strDepartmentName_ForCreate As String = strDepartment(intCounterForCreate)
        Dim strManagerID_ForCreate As String = strManagerID(intCounterForCreate)
        Dim strDateValid_ForCreate As String = strDateValid(intCounterForCreate)
        Dim strCompany_ForCreate As String = strCompany(intCounterForCreate)
        Dim strRegion_ForCreate As String = strRegion(intCounterForCreate)
        Dim strCity_ForCreate As String = strCity(intCounterForCreate)
        Dim strStreet_ForCreate As String = strStreet(intCounterForCreate)
        Dim strPostalCode_ForCreate As String = strPostalCode(intCounterForCreate)
        Dim strCountry_ForCreate As String = strCountry(intCounterForCreate)
        Dim strCountryCode_ForCreate As String = strCountryCode(intCounterForCreate)
        Dim strCountryAbr_ForCreate As String = strCountryAbr(intCounterForCreate)
        Dim strPhone_ForCreate As String = strPhone(intCounterForCreate)
        Dim strTargeOU_ForCreate, strsAMAccountName_ForCreate, strManagerDN, strUserDN_ForCreate As String
        Dim strPassword, strTableIn As String
        Dim strPath As String          ' Binding path.
        strTableIn = "Employee_Logs"
        strTargeOU_ForCreate = GetDN_OU_byID(strDepartmentID_ForCreate, strRootAD)

        If strTargeOU_ForCreate <> String.Empty Then
            If CheckUserbyDN("cn=" & strFullName_ForCreate & "," & strTargeOU_ForCreate, strRoot) Then Exit Function

            If strGivenName_ForCreate <> String.Empty Then
                strPath = "LDAP://" & strTargeOU_ForCreate
                Using de As New DirectoryEntry(strPath)
                    de.RefreshCache()
                    'Dim deUser As DirectoryEntry
                    Using deUser = de.Children.Add("CN=" & strFullName_ForCreate, "user")

                        Try
                            strsAMAccountName_ForCreate = CreateSAM(strLastName_ForCreate, strGivenName_ForCreate, strMiddleName_ForCreate)
                            deUser.Properties("sAMAccountName").Value = strsAMAccountName_ForCreate
                            deUser.CommitChanges()
                            intCounterCreateUser = intCounterCreateUser + 1
                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Created user accaunt for " & strFullName_ForCreate)
                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, strFullName_ForCreate & "Written down value sAMAccountName " & strsAMAccountName_ForCreate)
                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & "Created user accaunt for " & strFullName_ForCreate)
                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value sAMAccountName " & strsAMAccountName_ForCreate)
                        Catch ex As Exception
                            Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value sAMAccountName " & strFullName_ForCreate & ";" & ex.Message)
                            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value логина sAMAccountName " & strFullName_ForCreate & ";" & ex.Message)
                            Console.WriteLine("Error:   Create failed.")
                        End Try

                        If strsAMAccountName_ForCreate & strUPN <> String.Empty Then
                            Try
                                deUser.Properties("userPrincipalName").Value = strsAMAccountName_ForCreate & strUPN
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value userPrincipalName " & strsAMAccountName_ForCreate & strUPN)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value userPrincipalName " & strsAMAccountName_ForCreate & strUPN)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value userPrincipalName " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value userPrincipalName " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strDateValid_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("adminDescription").Add(strDateValid_ForCreate)
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value adminDescription " & strDateValid_ForCreate)
                                strOutputFileCreateOULog.AppendLine(Now.ToString & " ; " & strFullName_ForCreate & "; Written down value adminDescription " & strDateValid_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strDepartmentID_ForCreate, strDepartmentName_ForCreate, "Error writing value adminDescription " & strEmployeeID_ForCreate & "; " & strDepartmentName_ForCreate & "; " & ex.Message)
                                strOutputFileErrorOULog.AppendLine(Now.ToString & " ; Error writing value adminDescription " & strFullName_ForCreate & "; " & strDepartmentID_ForCreate & "; " & ex.Message)
                            End Try
                        End If

                        If strLastName_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("sn").Value = strLastName_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value sn " & strLastName_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value sn " & strLastName_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value sn " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value sn " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strGivenName_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("givenName").Value = strGivenName_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value givenName " & strGivenName_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value givenName " & strGivenName_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value givenName " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value givenName " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strMiddleName_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("middleName").Value = strMiddleName_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value middleName " & strMiddleName_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value отчества MiddleName " & strMiddleName_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing middleName " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value middleName " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strFullName_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("displayName").Value = strFullName_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value displayName " & strFullName_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value displayName " & strFullName_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value displayName " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value displayName " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strEmployeeID_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("employeeID").Value = strEmployeeID_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value employeeID " & strEmployeeID_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value employeeID " & strEmployeeID_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value employeeID " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value employeeID " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If


                        If strEmployeeNumber_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("employeeNumber").Value = strEmployeeNumber_ForCreate
                                deUser.CommitChanges()

                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value employeeNumber " & strEmployeeNumber_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value employeeNumber " & strEmployeeID_ForCreate)
                                strCurrentDN = GetDN_User_byID(strEmployeeID(intCounterForCreate), strRootAD)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value employeeNumber " & strEmployeeNumber_ForCreate)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value employeeNumber " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strEmployeeType_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("employeeType").Value = strEmployeeType_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value employeeType " & strEmployeeType_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value employeeType " & strEmployeeType_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value employeeType " & strEmployeeType_ForCreate)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value employeeType " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strBirthDate_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("extensionAttribute7").Value = strBirthDate_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value extensionAttribute7 " & strBirthDate_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value extensionAttribute7 " & strBirthDate_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value extensionAttribute7 " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value extensionAttribute7 " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strJobTitle_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("title").Value = strJobTitle_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value Title " & strJobTitle_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value  Title " & strJobTitle_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value title " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value title " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strFullJobTitle_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("description").Value = strFullJobTitle_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value description " & strFullJobTitle_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value description " & strFullJobTitle_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value description " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value description " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strDepartmentID_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("departmentNumber").Value = strDepartmentID_ForCreate       ' AD	departmentNumber
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value departmentNumber " & strDepartmentID_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value departmentNumber " & strDepartmentID_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value departmentNumber " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value departmentNumber " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strDepartmentName_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("department").Value = strDepartmentName_ForCreate              ' AD	department
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value department " & strDepartmentName_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down valuedepartment " & strDepartmentName_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value department " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value department " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strPhone_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("telephoneNumber").Value = strPhone_ForCreate              ' AD	telephoneNumber
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value telephoneNumber " & strPhone_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value telephoneNumber " & strPhone_ForCreate)
                            Catch ex As Exception
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value telephoneNumber " & strFullName_ForCreate & ";" & ex.Message)
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value telephoneNumber " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strManagerID_ForCreate <> String.Empty Then

                            Select Case IsManagerActive(strManagerID_ForCreate)
                                Case "fired"
                                    Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error in checking data for " & strFullName_ForCreate & ". Manager with EmployeeID " & strManagerID_ForCreate & " has status fired.")
                                    strOutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error in checking data for " & strFullName_ForCreate & ". Manager with EmployeeID " & strManagerID_ForCreate & " has status fired.")
                                Case "hired"
                                    strManagerDN = GetDN_User_byID(strManagerID_ForCreate, strRoot)
                                    strUserDN_ForCreate = GetDN_User_byID(strEmployeeID_ForCreate, strRoot)
                                    If strManagerDN <> String.Empty And strManagerDN <> strUserDN_ForCreate Then
                                        Try
                                            deUser.Properties("manager").Value = strManagerDN
                                            deUser.CommitChanges()
                                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value manager " & strManagerDN)
                                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value manager " & strManagerDN)
                                        Catch ex As Exception
                                            Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value manager " & strFullName_ForCreate & ";" & ex.Message)
                                            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value manager " & strFullName_ForCreate & ";" & ex.Message)
                                        End Try
                                    End If
                                Case "not found"
                                    Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error in checking data for" & strFullName_ForCreate & ". Manager with EmployeeID " & strManagerID_ForCreate & " not found.")
                                    strOutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error in checking data for" & strFullName_ForCreate & ". Manager with EmployeeID " & strManagerID_ForCreate & " not found.")
                            End Select
                        End If

                        If strCity_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("l").Value = strCity_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value l " & strCity_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value l " & strCity_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value l " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value l " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strStreet_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("streetAddress").Value = strStreet_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value streetAddress " & strStreet_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value streetAddress " & strStreet_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value streetAddress " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value streetAddress " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strPostalCode_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("postalCode").Value = strPostalCode_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value postalCode " & strPostalCode_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value postalCode " & strPostalCode_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value postalCode " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value postalCode " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strRegion_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("st").Value = strRegion_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value st " & strRegion_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value st " & strRegion_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value st " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value st " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strCountry_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("co").Value = strCountry_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value co " & strCountry_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value co " & strCountry_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value co " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value co " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strCountryCode_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("countryCode").Value = strCountryCode_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value countryCode " & strCountryCode_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value countryCode " & strCountryCode_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value countryCode " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value countryCode " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strCountryAbr_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("c").Value = strCountryAbr_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value c " & strCountryAbr_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value c " & strCountryAbr_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value c " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value c " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If strCompany_ForCreate <> String.Empty Then
                            Try
                                deUser.Properties("company").Value = strCompany_ForCreate
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value company " & strCompany_ForCreate)
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value company " & strCompany_ForCreate)
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value company " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value company " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        If CreateHomeFolder(strEmployeeID_ForCreate, strsAMAccountName_ForCreate, strFullName_ForCreate) Then
                            Try
                                deUser.Properties("homeDrive").Value = "H:"
                                deUser.CommitChanges()
                                Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value homeDrive " & "H:")
                                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value homeDrive " & "H:")
                            Catch ex As Exception
                                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value homeDrive " & strFullName_ForCreate & ";" & ex.Message)
                                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value homeDrive " & strFullName_ForCreate & ";" & ex.Message)
                            End Try
                        End If

                        Try
                            deUser.Properties("homeDirectory").Value = strRootHomeDir & strsAMAccountName_ForCreate
                            deUser.CommitChanges()
                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value homeDirectory " & strRootHomeDir & strsAMAccountName_ForCreate)
                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value homeDirectory " & strRootHomeDir & strsAMAccountName_ForCreate)
                        Catch ex As Exception
                            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value homeDirectory " & strFullName_ForCreate & ";" & ex.Message)
                            Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value homeDirectory " & strFullName_ForCreate & ";" & ex.Message)
                        End Try

                        Try
                            deUser.Invoke("SetPassword", New Object() {"#7Green&"})
                            deUser.CommitChanges()
                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value intial password " & strPassword)
                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value intial password " & strPassword)
                        Catch ex As Exception
                            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing intial password " & strFullName_ForCreate & ";" & ex.Message)
                            Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value intial password " & strFullName_ForCreate & ";" & ex.Message)
                        End Try

                        Try
                            deUser.Properties("userAccountControl").Value = "544" ' 544 - Account Enabled and Require user to change password at first logon 
                            deUser.CommitChanges()
                            Call WriteToSQL_Logs(strTableIn, "Create", strEmployeeID_ForCreate, strFullName_ForCreate, "Written down value userAccountControl " & "544")
                            strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; Written down value userAccountControl " & "544")
                        Catch ex As Exception
                            Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "Error writing value userAccountControl " & strFullName_ForCreate & ";" & ex.Message)
                            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & "Error writing value userAccountControl " & strFullName_ForCreate & ";" & ex.Message)
                        End Try


                    End Using
                End Using
            Else
                Call WriteToSQL_Logs(strTableIn, "Error", strEmployeeID_ForCreate, strFullName_ForCreate, "; User " & strFullName_ForCreate & " does not have a given name. The account will not be created.")
                OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreate & "; User " & strFullName_ForCreate & " does not have a given name. The account will not be created.")

            End If

        End If

    End Function



    Function AddDirectorySecurity(ByVal strDirectoryName As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal Flag As InheritanceFlags, ByVal ControlType As AccessControlType) As Boolean

        ' Create a new DirectoryInfoobject.
        If Directory.Exists(strDirectoryName) Then
            Dim dInfo As New DirectoryInfo(strDirectoryName)

            ' Get a DirectorySecurity object that represents the current security settings.
            Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
            dSecurity.SetAccessRuleProtection(True, False)
            ' Add the FileSystemAccessRule to the security settings (**following is one line of code**).
            dSecurity.AddAccessRule(New FileSystemAccessRule(Account, Rights, (InheritanceFlags.ContainerInherit +
            InheritanceFlags.ObjectInherit), PropagationFlags.None, ControlType))

            ' Set the new access settings.
            dSecurity.SetAccessRuleProtection(True, True)
            Try
                dInfo.SetAccessControl(dSecurity)
                Return True
            Catch ex As Exception
                Return False
            Finally
                dSecurity = Nothing
                dInfo = Nothing
            End Try
        Else
        End If

    End Function


    Function CreateHomeFolder(strUserID As String, strUserLogon As String, strFullName_ForCreateHomeDir As String) As Boolean

        Dim strTableIn As String = "Employee_Logs"

        Dim strDirectory As String
        strDirectory = strRootHomeDir & strUserLogon
        ' Create the File System Object
        If Not (Directory.Exists(strRootHomeDir)) Then
            Directory.CreateDirectory(strRootHomeDir)
            Call WriteToSQL_Logs(strTableIn, "Error", strUserID, strFullName_ForCreateHomeDir, strRootHomeDir & " does not exist")
            OutputFileErrorUserLog.AppendLine(Now.ToString & "; " & strRootHomeDir & " does not exist ")
        End If

        Try
            If (Directory.Exists(strDirectory)) Then
                Call WriteToSQL_Logs(strTableIn, "UserWarningLog", strUserID, strFullName_ForCreateHomeDir, strDirectory & " already exists.")
                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; " & strFullName_ForCreateHomeDir & " " & strDirectory & " already exists.")
            Else
                Directory.CreateDirectory(strDirectory)
                Call AddDirectorySecurity(strDirectory, "Administrators", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit + InheritanceFlags.ContainerInherit, AccessControlType.Allow)
                Call AddDirectorySecurity(strDirectory, strUserLogon, FileSystemRights.Modify, InheritanceFlags.ContainerInherit + InheritanceFlags.ObjectInherit, AccessControlType.Allow)
                Call WriteToSQL_Logs(strTableIn, "Create", strUserID, strFullName_ForCreateHomeDir, "Home drive " & strDirectory & " created successfully.")
                strOutputFileCreateUserLog.AppendLine(Now.ToString & "; Home drive " & strDirectory & " created successfully.")
            End If
            Return True
        Catch E As Exception
            Call WriteToSQL_Logs(strTableIn, "Error", strUserID, strFullName_ForCreateHomeDir, "Error writing value " & strFullName_ForCreateHomeDir)
            OutputFileErrorUserLog.AppendLine(Now.ToString & "; Error writing value " & strFullName_ForCreateHomeDir)
            Return False
        End Try

    End Function
    Function IsManagerActive(strID As String) As String
        Dim strDN As String = GetDN_User_byID(strID, strRootAD)
        If strDN <> String.Empty Then
            If strDN.IndexOf(strHRSync) = -1 Then
                IsManagerActive = "hired"
            Else
                IsManagerActive = "fired"
            End If
        Else
            IsManagerActive = "not found"
        End If
    End Function
    Sub CheckUser(ByVal intCounterForCheck As Integer)
        Dim strFullName_ForCheck As String = strFullName(intCounterForCheck)
        Dim strLastName_ForCheck As String = strLastName(intCounterForCheck)
        Dim strGivenName_ForCheck As String = strGivenName(intCounterForCheck)
        Dim strMiddleName_ForCheck As String = strMiddleName(intCounterForCheck)
        Dim strEmployeeID_ForCheck As String = strEmployeeID(intCounterForCheck)
        Dim strEmployeeNumber_ForCheck As String = strEmployeeNumber(intCounterForCheck)
        Dim strEmployeeType_ForCheck As String = strEmployeeType(intCounterForCheck)
        Dim strBirthDate_ForCheck As String = strBirthDate(intCounterForCheck)
        Dim strJobTitle_ForCheck As String = strJobTitle(intCounterForCheck)
        Dim strFullJobTitle_ForCheck As String = strFullJobTitle(intCounterForCheck)
        Dim strDepartmentID_ForCheck As String = strDepartmentID(intCounterForCheck)
        Dim strDepartmentName_ForCheck As String = strDepartment(intCounterForCheck)
        Dim strManagerID_ForCheck As String = strManagerID(intCounterForCheck)
        Dim strCompany_ForCheck As String = strCompany(intCounterForCheck)
        Dim strRegion_ForCheck As String = strRegion(intCounterForCheck)
        Dim strCity_ForCheck As String = strCity(intCounterForCheck)
        Dim strStreet_ForCheck As String = strStreet(intCounterForCheck)
        Dim strPostalCode_ForCheck As String = strPostalCode(intCounterForCheck)
        Dim strCountry_ForCheck As String = strCountry(intCounterForCheck)
        Dim strCountryCode_ForCheck As String = strCountryCode(intCounterForCheck)
        Dim strCountryAbr_ForCheck As String = strCountryAbr(intCounterForCheck)
        Dim strPhone_ForCheck As String = strPhone(intCounterForCheck)
        Dim strDNameUpdateUser, strManagerDN As String

        strDNameUpdateUser = GetDN_User_byID(strEmployeeID_ForCheck, strRootAD)

        If strDNameUpdateUser = String.Empty Then Exit Sub

        ' Bind to the object to be moved.
        Using deUser As New DirectoryEntry("LDAP://" & strDNameUpdateUser)
            deUser.RefreshCache()

            If (strLastName_ForCheck <> deUser.Properties("sn").Value And strLastName_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "sn", strLastName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strGivenName_ForCheck <> deUser.Properties("givenName").Value And strGivenName_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "givenName", strGivenName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If


            If (strMiddleName_ForCheck <> deUser.Properties("middleName").Value And strMiddleName_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "middleName", strMiddleName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strEmployeeNumber_ForCheck <> deUser.Properties("EmployeeNumber").Value And strEmployeeNumber_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "EmployeeNumber", strEmployeeNumber_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strEmployeeType_ForCheck <> deUser.Properties("EmployeeType").Value And strEmployeeType_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "EmployeeType", strEmployeeType_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strBirthDate_ForCheck <> deUser.Properties("extensionAttribute7").Value And strBirthDate_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "extensionAttribute7", strBirthDate_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strJobTitle_ForCheck <> deUser.Properties("Title").Value And strJobTitle_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "Title", strJobTitle_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If


            If (strDepartmentName_ForCheck <> deUser.Properties("department").Value And strDepartmentName_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "department", strDepartmentName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strDepartmentID_ForCheck <> deUser.Properties("departmentNumber").Value And strDepartmentID_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "departmentNumber", strDepartmentID_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If (strCompany_ForCheck <> deUser.Properties("company").Value And strCompany_ForCheck <> String.Empty) Then
                UpdateProperty(strDNameUpdateUser, "company", strCompany_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strRegion_ForCheck <> deUser.Properties("st").Value Then
                UpdateProperty(strDNameUpdateUser, "st", strRegion_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strCity_ForCheck <> deUser.Properties("l").Value Then
                UpdateProperty(strDNameUpdateUser, "l", strCity_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strStreet_ForCheck <> deUser.Properties("streetAddress").Value Then
                UpdateProperty(strDNameUpdateUser, "streetAddress", strStreet_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strPostalCode_ForCheck <> deUser.Properties("postalCode").Value Then
                UpdateProperty(strDNameUpdateUser, "postalCode", strPostalCode_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strCountry_ForCheck <> deUser.Properties("co").Value Then
                UpdateProperty(strDNameUpdateUser, "co", strCountry_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strCountryCode_ForCheck <> deUser.Properties("countryCode").Value Then
                UpdateProperty(strDNameUpdateUser, "countryCode", strCountryCode_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strCountryAbr_ForCheck <> deUser.Properties("c").Value Then
                UpdateProperty(strDNameUpdateUser, "c", strCountryAbr_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strPhone_ForCheck <> deUser.Properties("telephoneNumber").Value Then
                UpdateProperty(strDNameUpdateUser, "telephoneNumber", strPhone_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

            If strManagerID_ForCheck = String.Empty Then Exit Sub
            strManagerDN = GetDN_User_byID(strManagerID_ForCheck, strRoot)
            If strManagerDN = String.Empty Then Exit Sub
            If strManagerDN <> strDNameUpdateUser And strManagerDN <> deUser.Properties("manager").Value Then

                Select Case IsManagerActive(strManagerID_ForCheck)
                    Case "fired"
                        ClearProperty(strDNameUpdateUser, "manager", strEmployeeID_ForCheck, "Employee_Logs", "User")
                    Case "hired"
                        UpdateProperty(strDNameUpdateUser, "manager", strManagerDN, strEmployeeID_ForCheck, "Employee_Logs", "User")
                        intCounterUpdateUser = intCounterUpdateUser + 1
                    Case "not found"
                        ClearProperty(strDNameUpdateUser, "manager", strEmployeeID_ForCheck, "Employee_Logs", "User")
                End Select

            End If  ' End strManagerUpdateUser<>string.Empty 

            If deUser.Properties("cn").Value <> strFullName_ForCheck Then
                RenameProperty(strDNameUpdateUser, "cn", strFullName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
                strDNameUpdateUser = GetDN_User_byID(strEmployeeID_ForCheck, strRoot)
                UpdateProperty(strDNameUpdateUser, "displayName", strFullName_ForCheck, strEmployeeID_ForCheck, "Employee_Logs", "User")
            End If

        End Using
    End Sub
    Function TimeDiff(ByVal strStartTime As DateTime, ByVal strEndTime As DateTime) As String
        Dim dFrom As DateTime
        Dim dTo As DateTime
        Dim Result As String

        If DateTime.TryParse(strStartTime, dFrom) AndAlso DateTime.TryParse(strEndTime, dTo) Then
            Dim TS As TimeSpan = dTo - dFrom
            Dim hour As Integer = TS.Hours
            Dim mins As Integer = TS.Minutes
            Dim secs As Integer = TS.Seconds
            Dim msecs As Integer = TS.Milliseconds
            Result = (hour.ToString("00") & ":") + (mins.ToString("00") & ":") + (secs.ToString("00") & ":") + (msecs.ToString("000") & ":")
        End If
        Return Result
    End Function




End Module
